import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../Login/LoginVIewController.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import '../../http/getapi.dart';
class ChangNewPhoneNumber extends StatefulWidget {
  const ChangNewPhoneNumber({super.key});

  @override
  State<ChangNewPhoneNumber> createState() => _ChangNewPhoneNumberState();
}

class _ChangNewPhoneNumberState extends State<ChangNewPhoneNumber> {


  late Timer _timer;
  int curentTimer=0;
  bool isTimerRunning = false;
  String newPhone="";
  String smsCode="";
  String validCodeReqNo="";
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();

  }
  void startTimer() {
    setState(() {
      curentTimer = 60;
      isTimerRunning = true; // 设置定时器正在运行
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        curentTimer--;
        if (curentTimer == 0) {
          _timer.cancel();
          isTimerRunning = false; // 定时器结束后设置为非运行状态
          print("Timer ended");

          if (mounted) {
            setState(() {}); // 刷新状态以使按钮可点击
          }
        }
        if (!mounted) {
          _timer.cancel(); // 防止在组件被销毁后仍然运行定时器
        }
        setState(() {});
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor:Colors.white,
        centerTitle: true,
        title: Text("修改手机号",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: ListView(
        children: [
          Container(
            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 15.h,bottom: 15.h),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Column(
              children: [
                Row(
                  children: [
                    Text("*",style: TextStyle(color: MyColors.themeColor),),
                    Text("新手机号",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    SizedBox(width: 20.w,),
                    Container(
                      width: screenSize.width-150.w,
                      height: 35.h,
                      decoration: BoxDecoration(
                        color: MyColors.backgreyColor,
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                      child:  TextField(
                        decoration: InputDecoration(
                          hintText: '必填，请输入',
                          hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                          filled: true,
                          fillColor: MyColors.backgreyColor,
                          border: InputBorder.none,
                          alignLabelWithHint: true,
                          // contentPadding:EdgeInsets.only(left: 5.w,bottom: 5.h),

                        ),
                        keyboardType: TextInputType.number,
                        textAlign: TextAlign.left,
                        style: TextStyle(color: Colors.black),
                        onChanged: (value) {
                          setState(() {
                            newPhone=value;
                            print(value);
                          });
                        },
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 15.h,),
                Row(
                  children: [
                    Text("*",style: TextStyle(color: MyColors.themeColor),),
                    Text("验证码",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    SizedBox(width: 36.w,),
                    Container(
                      decoration: BoxDecoration(
                        color: MyColors.backgreyColor,
                        borderRadius: BorderRadius.all(Radius.circular(3)),
                      ),
                      height: 35.h,
                      width: screenSize.width-180,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            width: 120.w,
                            height: 35.h,
                            child:  TextField(
                              decoration: InputDecoration(
                                hintText: '必填，请输入',
                                hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                                filled: true,
                                fillColor: MyColors.backgreyColor,
                                border: InputBorder.none,
                                alignLabelWithHint: true,
                                // contentPadding:EdgeInsets.only(left: 5.w,top: 5.h,bottom: 5.h),
                              ),
                              keyboardType: TextInputType.number,
                              textAlign: TextAlign.left,
                              style: TextStyle(color: Colors.black),
                              onChanged: (value) {
                                setState(() {
                                  smsCode=value;
                                  print(value);
                                });
                              },
                            ),
                          ),
                          GestureDetector(
                            onTap: (){
                              if(newPhone==""){
                                BrnToast.show("请输入手机号码", context, duration: BrnDuration.short,);
                              }else{
                              if(curentTimer==0) {
                                startTimer();
                                if (isTimerRunning){
                                  String phoneNum = newPhone;
                                  ApiManager.postData(
                                    context,
                                    'api/auth/auth/shipper/sendNewPhoneValidCode',
                                    {
                                      "phone":phoneNum,
                                    },
                                        (responseData) async {
                                      BrnToast.show("验证码发送成功", context, duration: BrnDuration.short,);
                                      validCodeReqNo=responseData['data']['validCodeReqNo'];

                                    },
                                  );
                                }
                              }
                              }
                            },
                         child: curentTimer > 0?Text(curentTimer.toString() +"s重新获取",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),)
                    :Text("获取验证码",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),)),



                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 8.h,left: 10.w),
            child:Text("*新手机号需在速配货未注册过的手机号。",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
          ),
          Container(
            margin: EdgeInsets.only(left: 10.w),
            child:Text("*更换手机号时效5分钟，过期后需重新验证身份信息。",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
          ),
          SizedBox(height: 50.h,),
          Container(margin: EdgeInsets.only(left: 15.w,right: 15.w),
            child:    BrnSmallMainButton(
              title: '提交',
              bgColor: MyColors.themeColor,
              fontSize: 16.sp,
              radius: 30,
              onTap: () {
                if(smsCode!=""){
                  ApiManager.postData(
                    context,
                    'api/auth/auth/shipper/checkNewPhoneValidCode',
                    {
                      "phone": newPhone,
                      "validCode":smsCode,
                      "validCodeReqNo":validCodeReqNo,
                    },
                        (responseData) async {
                      BrnToast.show("修改成功", context, duration: BrnDuration.short,);
                      TokenManager.clearToken();
                      Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(builder: (builder) {
                            return LoginVC();
                          }), (route) => route == null);


                    },
                  );


                }else{
                  BrnToast.show("请输入验证码", context, duration: BrnDuration.short,);
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}
